package com.shigui.news.controller;


import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;


import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.shigui.news.dao.UserDao;
import com.shigui.news.dao.impl.UserDaoImpl;
import com.shigui.news.enums.ResponseCode;
import com.shigui.news.exception.UserException;
import com.shigui.news.model.User;

public class BaseAction extends ActionSupport {
	
	private Integer page = new Integer(1);
	private Integer count = new Integer(10);
	private Integer total;
	public static final Integer N = 1;
	
	@Autowired
	private UserDao userDao;
	
	protected User findByPersistCode(){
		Map<String, Object> session = ActionContext.getContext().getSession();
		
		if(session.containsKey(User.SESSION_PERSIST_KEY) && 
				session.containsKey(User.SESSION_USER_KEY)){
			String persistCode = (String) session.get(User.SESSION_PERSIST_KEY);
			
			
			User loginUser = userDao.findByPersistCode(persistCode);
			User sessionUser = (User) session.get(User.SESSION_USER_KEY);
			
			if(loginUser != null && 
					loginUser.getCipherPassword().equals(sessionUser.getCipherPassword())){
				session.put(User.SESSION_USER_KEY, loginUser);
				
				return loginUser;
			}else{
				return null;
			}
		
			
		}
		return null;
	}	

	public User findByPersistCodeOrFail(){
		User loginUser = findByPersistCode();
		
		if(loginUser == null){
			throw new UserException(ResponseCode.USER_ALREADY_LOGOUT);
		}else{
			return loginUser;
		}
	}


	public Integer getPage() {
		return page;
	}

	public void setPage(Integer page) {
		if(page != null && page > 0){
			
			this.page = page;
		}
	}

	public Integer getCount() {
		return count;
	}

	public void setCount(Integer count) {
		
		if(count != null && count > 0){
			
			this.count = count;
		}
	}

	/**
	 * 这个地方很重要
	 * 可能会弄错，搞成无线递归
	 * @return
	 */
	public Integer getTotalPage(){
		if(total == null ){
			return 0;
		}
		
		return (int) Math.ceil(((double)getTotal()/(double)count));
	}
	
	public Integer getTotal() {
		return this.total;
	}

	public void setTotal(Integer total) {
		this.total = total;
	}
	public HttpServletRequest getHttpRequest(){
		return ServletActionContext.getRequest();
	}
	
	public HttpServletResponse getHttpResponse(){
		return ServletActionContext.getResponse();
	}
	
	public HttpSession getHttpSession(){
		HttpSession session = getHttpRequest().getSession();
		session.setMaxInactiveInterval(7200);
		
		return session;
	}
	
	

	
	
	
}
